package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.StgyException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.AttrValue;
import com.atguigu.lease.model.entity.FeeKey;
import com.atguigu.lease.model.entity.FeeValue;
import com.atguigu.lease.web.admin.mapper.FeeKeyMapper;
import com.atguigu.lease.web.admin.service.FeeKeyService;
import com.atguigu.lease.web.admin.service.FeeValueService;
import com.atguigu.lease.web.admin.vo.fee.FeeKeyVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author gqs
 * @description 针对表【fee_key(杂项费用名称表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class FeeKeyServiceImpl extends ServiceImpl<FeeKeyMapper, FeeKey> implements FeeKeyService {
  @Autowired private FeeKeyMapper mapper;
  @Autowired private FeeValueService feeValueService;

  @Override
  public List<FeeKeyVo> listFeeInfo() {
    // return mapper.listFeeInfo();

    // 用stream流的方式返回数据列表
    List<FeeKey> feeKeys = this.list();
    // stream() 将 feeKeys 集合转换为一个 Stream，
    // 然后使用 map 方法对 Stream 中的每个元素进行转换。
    // 对于每个 FeeKey 对象，创建一个新的 FeeKeyVo 对象，
    return feeKeys.stream()
        .map(
            feeKey -> {
              FeeKeyVo feeKeyVo = new FeeKeyVo();
              // BeanUtils 可以将数据源对象的相同类型相同名称的属性值赋值给目标对象
              // 使用 BeanUtils.copyProperties 方法将 FeeKey 对象的属性复制到 FeeKeyVo 对象中。
              BeanUtils.copyProperties(feeKey, feeKeyVo);
              // 调用 feeValueService.list() 方法来查询与当前 FeeKey 对象关联的所有 FeeValue 对象，
              // 并将查询结果设置为 feeKeyVo 对象的 feeValueList 属性
              feeKeyVo.setFeeValueList(
                  feeValueService.list(
                      Wrappers.lambdaQuery(FeeValue.class)
                          .eq(FeeValue::getFeeKeyId, feeKey.getId())));
              // 返回转换后的vo对象
              return feeKeyVo;
            })
        .collect(Collectors.toList());
  }

  @Override
  public boolean saveOrUpdateFeeKey(FeeKey feeKey) {
    Long id = feeKey.getId() == null ? -1 : feeKey.getId();

    FeeKey dbFeeKey =
        this.getOne(
            Wrappers.lambdaQuery(FeeKey.class)
                .eq(FeeKey::getName, feeKey.getName())
                .last("limit 1"));
    if (dbFeeKey != null && !dbFeeKey.getId().equals(id)) {
      throw new StgyException(ResultCodeEnum.FEE_KEY_EXISTS_ERROR);
    }
    return this.saveOrUpdate(feeKey);
  }

  @Override
  public boolean removeAllById(Long feeKeyId) {
    this.removeById(feeKeyId);
    feeValueService.remove(
        Wrappers.lambdaQuery(FeeValue.class).eq(FeeValue::getFeeKeyId, feeKeyId));
    return true;
  }
}
